class Task {
  maxTask: number = 10;
  totalTask: number = 0;
  successNum: number = 0;
  list: {
    willList: any[];
    failList: any[];
    runningList: any[];
  } = {
    willList: [],
    failList: [],
    runningList: []
  };

  add = task => {
    this.totalTask++;
    this.list.willList.push(task);
    this.run();
  };
  getTasksNumber = () => {
    let { willList, runningList, failList } = this.list;
    return {
      willListLength: willList.length,
      runningListLength: runningList.length,
      failListLength: failList.length,
      successLength: this.successNum,
      totalTask: this.totalTask,
      curOthers: runningList.map(item => {
        return item.other;
      }),
      others: willList
        .filter((a, i) => i > willList.length - 100)
        .map(item => {
          return item.other;
        })
    };
  };

  run = () => {
    let { willList, runningList, failList } = this.list;
    if (willList.length && runningList.length < this.maxTask) {
      // let tempTask = willList.shift();
      let tempTask = willList.pop();
      runningList.push(tempTask);
      tempTask().then(
        res => {
          this.successNum++;
          runningList.splice(runningList.indexOf(tempTask), 1);
          this.run();
        },
        () => {
          runningList.splice(runningList.indexOf(tempTask), 1);
          failList.push(tempTask);
          this.run();
        }
      );
    }
  };
}

const taskCenter = new Task();

export { taskCenter };
